package com.example.testapp.activity.adapter;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ImageSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.testapp.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by l on 2016/6/30.
 */
public class MainPagerAdapter extends FragmentPagerAdapter {

    private List<Fragment> fragmentList = new ArrayList<>();
    private List<String>   titlesList = new ArrayList<>();
    private Context  mContext;

    private int[] imageResId = {R.mipmap.facebook_logo_32, R.mipmap.facebook_logo_32, R.mipmap.facebook_logo_32, R.mipmap.facebook_logo_32};
    private int[] drawImagesId={R.drawable.select_tab_layout,R.drawable.select_tab_layout,R.drawable.select_tab_layout,R.drawable.select_tab_layout};

    public MainPagerAdapter(FragmentManager fm, Context context) {
        super(fm);
        this.mContext = context;
    }

    @Override
    public Fragment getItem(int position) {
        return fragmentList.get(position);
    }

    @Override
    public int getCount() {
        return fragmentList.size();
    }

    @Override
    public CharSequence getPageTitle(int position) {
        Drawable  image = mContext.getResources().getDrawable(imageResId[position]);
        image.setBounds(0, 0, image.getIntrinsicWidth(), image.getIntrinsicHeight());
        SpannableString  sb = new SpannableString(" " + titlesList.get(position));
        ImageSpan  imageSpan = new ImageSpan(image, ImageSpan.ALIGN_BASELINE);
        sb.setSpan(imageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return sb;
    }

    public void addFragment(Fragment fragment, String titles) {
        fragmentList.add(fragment);
        titlesList.add(titles);
    }

    public View getTabView(int position) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.view_item_tablayout, null);
        TextView  tv = (TextView)view.findViewById(R.id.tab_item_txt);
        tv.setText(titlesList.get(position));
        ImageView img = (ImageView)view.findViewById(R.id.tabImage);
        img.setImageResource(drawImagesId[position]);
        return view;
    }
}
